import logging

import pymysql


# 封装数据库工具类
class DBUtil(object):
    conn = None

    @classmethod
    def __get_conn(cls):
        if cls.conn is None:
            cls.conn = pymysql.connect(host="211.103.136.244", port=7061, user="student",
                                       password='iHRM_student_2021', database="ihrm", charset="utf8")
        return cls.conn

    @classmethod
    def __close_conn(cls):
        if cls.conn is not None:
            cls.conn.close()
            cls.conn = None

    @classmethod
    def select_one(cls, sql):
        cursor = None
        result = None
        try:
            # 建立连接
            cls.conn = cls.__get_conn()
            logging.info("链接数据库成功")
            # 建立游标
            cursor = cls.conn.cursor()
            # 查询一行语句
            cursor.execute(sql)
            result = cursor.fetchone()
        except Exception as err:
            print('查询失败：', str(err))
        finally:
            # 关闭游标
            cursor.close()
            # 关闭连接
            cls.__close_conn()
            # 返回结果
            return result

    @classmethod
    def uid_db(cls, sql):
        cursor = None
        try:
            # 建立连接
            cls.conn = cls.__get_conn()
            # 建立游标
            cursor = cls.conn.cursor()

            # 执行增删改语句
            cursor.execute(sql)
            # 影响行数
            # print("影响行数：", cls.conn.affected_rows())
            logging.info(f"影响的行数：{cls.conn.affected_rows()}")
            # 提交事务
            cls.conn.commit()
        except Exception as err:
            cls.conn.rollback()
            # print("增删改失败：", str(err))
            logging.debug(f"'增删改失败：',{str(err)}")
        finally:
            # 关闭游标
            cursor.close()
            # 关闭连接
            cls.__close_conn()
